/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hisense.settings;
import com.android.settings.R;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.os.Message;

import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.text.format.DateFormat;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.util.Log;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import android.content.ContentResolver;
import android.preference.PreferenceManager; 

import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.Preference.OnPreferenceChangeListener;

public class PowerOffTimer  extends PreferenceActivity 
        implements Preference.OnPreferenceChangeListener{

	final static String M12 = "h:mm aa";
    final static String M24 = "kk:mm";
	final static String AUTO_ON_FLAG = "auto_on_flag";
	final static String AUTO_ON_HOUR = "auto_on_hour";
	final static String AUTO_ON_MINUTE = "auto_on_minute";
	final static String AUTO_OFF_FLAG = "auto_off_flag";
	final static String AUTO_OFF_HOUR = "auto_off_hour";
	final static String AUTO_OFF_MINUTE = "auto_off_minute";
	
	
	private boolean bAutoOnEnabled;
	private boolean bAutoOffEnabled;
	private int mAutoOnHour =0;
	private int mAutoOnMinute =0;
	private int mAutoOffHour =0;
	private int mAutoOffMinute =0;
    private Preference mCurrentTimeShowPref;
    private Preference mSetPowerOfftimer;

	
    private CheckBoxPreference mAutoOnEnabledPref;
    private Preference mAutoOnTimePref;
	private CheckBoxPreference mAutoOffEnabledPref;
    private Preference mAutoOffTimePref;
    private Activity mActivity;
    private ContentResolver mContentResolver; 
    SharedPreferences.Editor editor;
	
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
//        mActivity = getActivity();
//        mContentResolver = mActivity.getContentResolver(); 
        addPreferencesFromResource(R.xml.power_off_timer);  
		mSetPowerOfftimer =  findPreference("set_power_off_time");
		mSetPowerOfftimer.setOnPreferenceChangeListener(this);
       // initUI();        
		mCurrentTimeShowPref = findPreference("current_time_show");
        java.text.DateFormat shortDateFormat = DateFormat.getDateFormat(this);
        Date now = Calendar.getInstance().getTime();
        mCurrentTimeShowPref.setTitle(shortDateFormat.format(now)+" "+DateFormat.getTimeFormat(this).format(now));
        
        
//        SharedPreferences mPowerOfftimer = getSharedPreferences("com.google.tv.settings_preferences", Context.MODE_PRIVATE);  
       
        
       
    }

/**    
    public void initUI() {
       mAutoOnEnabledPref = (CheckBoxPreference)findPreference("auto_on");
	   mAutoOnTimePref =  findPreference("auto_on_time");
	   mAutoOffEnabledPref = (CheckBoxPreference)findPreference("auto_off");
	   mAutoOffTimePref =  findPreference("auto_off_time");
	   mAutoOnEnabledPref.setOnPreferenceChangeListener(this);
	   mAutoOnTimePref.setOnPreferenceChangeListener(this);
	   mAutoOffEnabledPref.setOnPreferenceChangeListener(this);
	   mAutoOffTimePref.setOnPreferenceChangeListener(this);	  
    }
**/
    @Override
    public void onResume() {
       super.onResume();
       
       SharedPreferences offuseontime = PreferenceManager.getDefaultSharedPreferences(this);
       SharedPreferences mPowerOfftimer = getSharedPreferences("com.android.settings_preferences", Context.MODE_PRIVATE);
	   
       Boolean off_use_on_time=offuseontime.getBoolean("off_use_on_time",false);
	   int PowerOffhour_summary=mPowerOfftimer.getInt("poweroff_hour", 0);
	   int PowerOffminute_summary=mPowerOfftimer.getInt("poweroff_minute", 0);
	   mSetPowerOfftimer.setSummary(PowerOffhour_summary+","+PowerOffminute_summary);
	   Log.i("poweroff_time",PowerOffhour_summary+","+PowerOffminute_summary+"@@@@@@@@@@@");
	   
       Log.i("off_use_on_time",off_use_on_time+"");
		if(off_use_on_time==false)
		{
			mSetPowerOfftimer.setEnabled(false);			
		}else
		{
			mSetPowerOfftimer.setEnabled(true);
		}
/*
	   if(1 == Settings.System.getInt(mContentResolver, AUTO_ON_FLAG, 0)) {
          bAutoOnEnabled  = true;
	   } else {
	 	  bAutoOnEnabled  = false;
	   }
	   mAutoOnEnabledPref.setChecked(bAutoOnEnabled);

	   if(1 == Settings.System.getInt(mContentResolver, AUTO_OFF_FLAG, 0)){
		  bAutoOffEnabled = true;
	   } else {
		 bAutoOffEnabled = false;
	   }

	   mAutoOffEnabledPref.setChecked(bAutoOffEnabled);
	   mAutoOnHour = Settings.System.getInt(mContentResolver, AUTO_ON_HOUR,0);		 
	   mAutoOnMinute = Settings.System.getInt(mContentResolver, AUTO_ON_MINUTE,0);
	   mAutoOnTimePref.setSummary(formatTime(mAutoOnHour,mAutoOnMinute));
	   mAutoOffHour = Settings.System.getInt(mContentResolver, AUTO_OFF_HOUR,0);
	   mAutoOffMinute = Settings.System.getInt(mContentResolver, AUTO_OFF_MINUTE,0);
       mAutoOffTimePref.setSummary(formatTime(mAutoOffHour,mAutoOffMinute));
	   mAutoOnTimePref.setEnabled(bAutoOnEnabled);
	   mAutoOffTimePref.setEnabled(bAutoOffEnabled);
*/
    }

    @Override 
    public void onPause() {
        super.onPause();    
    }
     
    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
       if (preference == mSetPowerOfftimer){
		  showTimePicker(true);
        }
        return false;
    }

	public boolean onPreferenceChange(final Preference p, Object newValue) {
/*
		if(p == mAutoOnEnabledPref){
			bAutoOnEnabled = !bAutoOnEnabled;
			Settings.System.putInt(mContentResolver, AUTO_ON_FLAG, 
                                bAutoOnEnabled ? 1 : 0);
			SendAutoOnOffSetIntent();
			mAutoOnTimePref.setEnabled(bAutoOnEnabled);

		}else if(p == mAutoOffEnabledPref){
			bAutoOffEnabled = !bAutoOffEnabled;
			Settings.System.putInt(mContentResolver, AUTO_OFF_FLAG, 
                                bAutoOffEnabled ? 1 : 0);
			SendAutoOnOffSetIntent();
			mAutoOffTimePref.setEnabled(bAutoOffEnabled);
		}
*/
		return true;
	}

	private void showTimePicker(boolean bPowerOn) {
		if(bPowerOn){
			SharedPreferences PowerOfftimer = getSharedPreferences("com.android.settings_preferences", Context.MODE_PRIVATE);
			int PowerOffhour_summary=PowerOfftimer.getInt("poweroff_hour", 0);
			int PowerOffminute_summary=PowerOfftimer.getInt("poweroff_minute", 0);
			mAutoOnHour=PowerOffhour_summary;
			mAutoOnMinute=PowerOffminute_summary;
			TimePickerDialog timepicker1 =  new TimePickerDialog(this, 
				
				new TimePickerDialog.OnTimeSetListener() {					
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
						SharedPreferences PowerOfftimer = getSharedPreferences("com.android.settings_preferences", Context.MODE_PRIVATE);
						
   					 	Calendar c = Calendar.getInstance();
   	                    c.set(Calendar.HOUR_OF_DAY, hourOfDay);
   	                    c.set(Calendar.MINUTE, minute);                                 	 
   				              //mAutoOnTimePref.setSummary(formatTime(mAutoOnHour,mAutoOnMinute));
					       //Settings.System.putInt(mContentResolver, AUTO_ON_HOUR, mAutoOnHour);
						//Settings.System.putInt(mContentResolver, AUTO_ON_MINUTE, mAutoOnMinute);
						 SendAutoOnOffSetIntent();
						 int hour=c.get(Calendar.HOUR_OF_DAY);
   	                     int minute_time=c.get(Calendar.MINUTE);
						 editor = PowerOfftimer.edit();
	                     editor.putInt("poweroff_hour", hour);
	                     editor.putInt("poweroff_minute", minute_time);
						 
						 mSetPowerOfftimer.setSummary(hour+","+minute_time);
						 
						 Log.i("poweroff_time",hour+","+minute_time+"%%%%%%%%%");
//						 Message msg = new Message();
//						 msg.what = 1;
////						 msg.arg1 = mAutoOnHour*60*60+mAutoOnMinute*60;
						 long poweroff_time=c.getTimeInMillis()-90*1000;
						 long currenttime = System.currentTimeMillis();
//						 PowerOffService.getPowerOffServiceInstance().getHandler().sendMessage(msg);
						 Log.i("cccc",poweroff_time-currenttime+"******"+currenttime);
						 editor.putLong("off_time", poweroff_time);
						 editor.putLong("current_time", currenttime);
						 editor.commit();
						 
						 Intent intent = new Intent();
						intent.setAction("com.google.poweroff");
						intent.putExtra("PowerOff_Time", poweroff_time);
						PowerOffTimer.this.sendBroadcast(intent);
					}
				}, 
				mAutoOnHour, 
				mAutoOnMinute,
                     	DateFormat.is24HourFormat(this));

     	              timepicker1.show();
     	             Log.i("mAutoOnHour", mAutoOnHour+"");
     	            
     	              
		}else{

			TimePickerDialog timepicker2=  new TimePickerDialog(this, 
				
				new TimePickerDialog.OnTimeSetListener() {					
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
						mAutoOffHour = hourOfDay;
   				        	mAutoOffMinute = minute;
   					 	Calendar c = Calendar.getInstance();
   	                                   c.set(Calendar.HOUR_OF_DAY, hourOfDay);
   	                                   c.set(Calendar.MINUTE, minute);                                 	 
   				              //mAutoOffTimePref.setSummary(formatTime(mAutoOffHour,mAutoOffMinute));
						//Settings.System.putInt(mContentResolver, AUTO_OFF_HOUR, mAutoOffHour);
						//Settings.System.putInt(mContentResolver, AUTO_OFF_MINUTE, mAutoOffMinute);
						SendAutoOnOffSetIntent();
					}
				}, 
				mAutoOffHour, 
				mAutoOffMinute,
                     	DateFormat.is24HourFormat(this));			
     	              timepicker2.show();
     	              Log.i("mAutoOffHour", mAutoOffHour+"");
     	             Log.i("mAutoOffMinute", mAutoOffMinute+"");
		}
       
    }

	public String formatTime(int hour, int minute)
	 {
		 String strFormat = DateFormat.is24HourFormat(this) ? M24 : M12;
		 Calendar c = Calendar.getInstance();
		 Date newDate = new Date();
		 newDate.setHours(hour);
		 newDate.setMinutes(minute);
		 c.setTime(newDate);
		 String strShowTime = (String)DateFormat.format(strFormat, c);
		 return strShowTime;
	 }

  public void SendAutoOnOffSetIntent(){
//  
//		Intent intent = new Intent("com.android.deskclock.AUTO_POWER_ON_OFF");
//	  Intent intent = new Intent();
//	  intent.setAction("android.intent.action.BOOT_COMPLETED");
//	  Bundle bundle  = new Bundle(); 
//      bundle.putInt("op", mAutoOnHour*60*60*1000);  
//      intent.putExtras(bundle);
      Log.i("111", System.currentTimeMillis()+"");
      Log.i("00000", mAutoOnHour+"");
      Log.i("00000", mAutoOnMinute+"");
//	  this.sendBroadcast(intent);
	  
//		mActivity.sendBroadcast(intent);	
//	  Intent intent = new Intent();
//	  intent.setClass(PowerOffTimer.this, Service.class);
//	  
  }

}

